import turf from 'turf';
import { zhejiangProvinceAdInfo } from '@/mixins/mapMixinsData';
const { center: defCenter, zoom: defZoom } = zhejiangProvinceAdInfo;
export function init ({ container, center = defCenter, zoom = defZoom }) {
  return new Promise((resolve, reject) => {
    const map = new mapboxgl.Map({
      container, // container id
      accessToken: 'pk.eyJ1IjoiY3VpemloYW8xOTkyIiwiYSI6ImNqa25lMmV6ZzAwdTAza3BjYXRqN3ozM3cifQ.TMJ1VTkOqGFQl4cyu0Jm3A',
      center,
      zoom,
      pitch: 0,
      bearing: 0,
      antialias: true,
      style: {
        version: 8,
        name: 'vue-map',
        metadata: {
          'mapbox:type': 'default'
        },

        bearing: 0,
        pitch: 0,
        sources: {},
        glyphs: '/offlinemap/fonts/{fontstack}/{range}.pbf',
        layers: [],
        created: '2020-02-19T10:24:27.291Z',
        modified: '2020-02-19T10:41:29.439Z',
        id: 'ck6t66b9m0ekp1ioboifd3o0k',
        owner: 'jimwei',
        visibility: 'private',
        draft: false
      },
      minZoom: 6.4,
      // minZoom: 1,
      maxZoom: 17,
      doubleClickZoom: false
    });
    map.on('load', function () {
      resolve(map);
    });
  });
}

export function checkLoaded (options) {
  return new Promise((resolve, reject) => {
    init(options).then(map => {
      const interval = setInterval(() => {
        if (map.loaded()) {
          resolve(map);
          clearInterval(interval);
        }
      }, 500);
    });
  });
}

export function addSourceMap ({ map, sources }) {
  for (const key in sources) {
    if (Object.prototype.hasOwnProperty.call(sources, key)) {
      map.addSource(key, sources[key]);
    }
  }
}

export function getFeaturesByApiData ({ datas, pointxLabel = 'lng', pointYLabel = 'lat' }) {
  // eslint-disable-next-line new-cap
  const features = new turf.featureCollection();
  features.features = [];
  datas.forEach(i => {
    features.features.push(turf.point([Number(i[pointxLabel]), Number(i[pointYLabel])], i));
  });
  return features;
}

// export function getLayersByIds ({ menus, checkedMenus }) {
//   const checkedLayers = {};
//   const unCheckedLayers = {};
//   menus.map(item => {
//     if (item.children && item.children.length) {
//       const { checkedLayers: cl, unCheckedLayers: uncl } = getLayersByIds({ menus: item.children, checkedMenus });
//       Object.assign(checkedLayers, cl);
//       Object.assign(unCheckedLayers, uncl);
//     }
//     const tarObj = checkedMenus.includes(item.menuId) ? checkedLayers : unCheckedLayers;
//     item.layers && item.layers.map(layerItem => {
//       tarObj[layerItem.id] = layerItem;
//     });
//   });
//   return { checkedLayers, unCheckedLayers };
// }

// export function intervalCheck (fn) {
//   return new Promise((resolve, reject) => {
//     const interval = setInterval(() => {
//       debugger;
//       if (fn()) {
//         resolve();
//         clearInterval(interval);
//       }
//     }, 200);
//   });
// }